unit Controllers.SessionController;

interface

uses
  System.Generics.Collections,
  Models.Usuario,
  Models.Acesso;

type
  TSessionController = class
  private
    FUsuario: TUsuario;
    FAcessos: TList<TAcesso>;
  public
    constructor Create; reintroduce;
    destructor Destroy; override;
    function ValidUserAndLoad(username, passowrd: string): boolean;
  private
    procedure LoadAccess;
  public
    property Usuario: TUsuario read FUsuario write FUsuario;
    property Acessos: TList<TAcesso> read FAcessos write FAcessos;
  end;

var
  SessionController: TSessionController;

implementation

uses
  DataAccess.UsuarioDAO, Controllers.AcessoController;

{ TSessionController }

constructor TSessionController.Create;
begin
  inherited;
end;

destructor TSessionController.Destroy;
var
  item: TAcesso;
begin
  if FUsuario <> nil then
    FUsuario.Free;
  if FAcessos <> nil then
    begin
      for item in FAcessos do
        item.Free;
      FAcessos.Free;
    end;
  inherited;
end;

function TSessionController.ValidUserAndLoad(username, passowrd: string): boolean;
var
  dao: TUsuarioDAO;
  user: TUsuario;
begin
  result := false;
  dao := TUsuarioDAO.Create;
  try
    user := dao.Get(username);
    if user <> nil then
      if user.Password = passowrd then
        result := true;
    if result then
      begin
        FUsuario := user;
        if not(FUsuario.NivelAcesso = naAdministrator) then
          LoadAccess;
      end;
  finally
    dao.Free;
  end;
end;

procedure TSessionController.LoadAccess;
var
  controller: TAcessoController;
begin
  controller := TAcessoController.Create;
  try
    FAcessos := controller.GetList(FUsuario.Username);
  finally
    controller.Free;
  end;
end;

initialization
  SessionController := TSessionController.Create;

finalization
  SessionController.Free;

end.
